package host

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"

	"gitee.com/shiwjlinux/arm/common"
)

type CreateHostRequest struct {
	Tags         map[string]string `json:"tags" gorm:"serializer:json"` // 标签
	Sn           string            `json:"sn" validate:"required"`      // SN
	Status       STATUS            `json:"status" gorm:"column:status"` // 状态 gorm 默认不修改零值 Status从1开始
	Summary      string            `json:"summary"`                     // 摘要
	CreateBy     string            `json:"create_by"`                   // 创建人
	Ip           string            `json:"ip"`                          //
	Hostname     string            `json:"hostname" validate:"required"`
	Type         string            `json:"type" `
	BuildVersion string            `json:"build_version"` //ro.build.version.name
}

func NewCreateHostRequest(sn, hostname string) *CreateHostRequest {
	return &CreateHostRequest{
		Tags:     make(map[string]string),
		Status:   STATUS_UNKNOW,
		Sn:       sn,
		Hostname: hostname,
	}
}

func (c *CreateHostRequest) String() string {
	return common.ToJsonString(c)
}

func (c *CreateHostRequest) Hash() string {
	if c == nil {
		return ""
	}
	// 客户端服务器做比较时，要忽略的字段

	hH := md5.New()
	b, _ := json.Marshal(c)
	hH.Write(b)
	hs := hex.EncodeToString(hH.Sum(nil))
	// fmt.Printf("hash string %s,%s\n", i.Names, hs)
	return hs
}

type Host struct {
	*common.Meta
	*CreateHostRequest
}

func NewHost(createHostRequest *CreateHostRequest) *Host {
	return &Host{
		Meta:              common.NewMeta(),
		CreateHostRequest: createHostRequest,
	}
}

func DefaultHost() *Host {
	return &Host{}
}

func (c *Host) Hash() string {
	if c == nil {
		return ""
	}
	// 客户端服务器做比较时，要忽略的字段
	c.UpdatedAt = 0
	c.CreatedAt = 0

	hH := md5.New()
	b, _ := json.Marshal(c)
	hH.Write(b)
	hs := hex.EncodeToString(hH.Sum(nil))
	// fmt.Printf("hash string %s,%s\n", i.Names, hs)
	return hs
}

func (c *Host) TableName() string {
	return AppName
}

func (c *Host) String() string {
	b, _ := json.MarshalIndent(c, " ", " ")
	return string(b)
}

type HostSet struct {
	Items []*Host `json:"items"`
	Total int64   `json:"total"`
}

func NewHostSet() *HostSet {
	return &HostSet{
		Items: make([]*Host, 0),
	}
}

func (c *HostSet) String() string {
	b, _ := json.MarshalIndent(c, " ", " ")
	return string(b)
}
